<?php

namespace app\common\model;

use app\common\controller\Helper;
use app\common\enums\StatusEnum;
use think\Model;

/**
 * 优惠券
 * Class Coupon
 * @package app\common\model
 */
class Coupon extends Model
{
    use Helper;

    protected $table = 'coupon';

    const NO_USE = 1;
    const USED = 2;
    const EXPIRED = 3;

    public static function attributes($attribute, $key = null)
    {
        $list = [
            'type' => [
                self::NO_USE => '未使用',
                self::USED => '已使用',
                self::EXPIRED => '已过期',
            ],
        ];
        return self::attributeReturn($list, $attribute, $key);
    }

    /**
     * 获取有效的优惠券列表，排除已经使用过的
     * @param $oauthId
     * @return false|\think\db\Query[]
     * @throws \think\Exception\DbException
     */
    public static function getListAll($oauthId)
    {
        // 已经使用的优惠券ID
        $ids = CouponUsed::getColumn($oauthId);
        $couponIds = array_keys($ids);

        $time = time();
        $sql = static::field('id, name, money')
            ->where('start_time', '<=', $time)
            ->where('end_time', '>=', $time)
            ->where(['status' => StatusEnum::ENABLED]);

        if ($couponIds) {
            $sql->where('id', 'not in', $couponIds);
        }

        return $sql->order(['sort_num' => 'desc', 'create_time' => 'desc'])
            ->select()
            ->toArray();
    }

    /**
     * 通过id获取优惠券的信息
     * @param $id
     * @return array|\PDOStatement|string|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getOne($id)
    {
        $time = time();
        $sql = static::field('id, name, money')
        ->where('start_time', '<=', $time)
        ->where('end_time', '>=', $time)
        ->where(['id' => $id, 'status' => StatusEnum::ENABLED])
        ->find();
        return static::field('id, name, money')
            ->where('start_time', '<=', $time)
            ->where('end_time', '>=', $time)
            ->where(['id' => $id, 'status' => StatusEnum::ENABLED])
            ->find();
    }
}